<template>
  <div>
    <Row type="flex" justify="center" align="middle">
      <Card shadow style="margin-top:10px">
        <Row style="width:375px;" type="flex">
          <i-col span="8">
            <i-select v-model="defaultIndex" @on-change="reset()">
              <i-option v-for="(item, i) in typeArr" :value="i" :key="i">{{item.type}}</i-option>
            </i-select>
          </i-col>
          <i-col span="16" style="text-align:right">
            <Upload action="/word-to-html" :on-success="handleSuccess">
              <Button icon="ios-cloud-upload-outline">导入文档</Button>
            </Upload>
          </i-col>
        </Row>
        <Row type="flex" justify="center">
          <Form ref="editorModel">
            <FormItem prop="content" style="margin-bottom:0">
              <textarea class="tinymce-textarea" id="tinymceEditer"></textarea>
            </FormItem>
          </Form>
          <Spin fix v-if="spinShow">
            <Icon type="load-c" size="18" class="demo-spin-icon-load"></Icon>
            <div>加载组件中...</div>
          </Spin>
        </Row>
      </Card>
    </Row>
    <Modal v-model="codeModal" title="代码" @on-ok="uploadFile" ok-text="上传">
      <template v-if="typeArr[defaultIndex].childType">
        <div
          class="radio-box"
          v-for="(item,i) in typeArr[defaultIndex].childType"
          :class="{checked:item.fn==checkFn}"
          :key="i">
          <label :for="item.type" @click="checkFn=item.fn"></label>
          <input :id="item.type" type="radio" :value="item.type" name="type" />
          {{item.type}}
        </div>
      </template>
      <p class="modalbody">{{code}}</p>
    </Modal>
    <Modal v-model="editModal" title="修改" @on-ok="setContent">
      <i-input type="textarea" placeholder="贴入你想修改的代码..." v-model="editCode"></i-input>
    </Modal>
  </div>
</template>
<script>
import axios from 'axios';
import qs from 'qs';
import tinymce from "tinymce";
import 'tinymce/themes/modern/theme';
import 'tinymce/skins/lightgray/skin.min.css';
import 'tinymce/skins/lightgray/content.min.css';
import util from "@/libs/util";
import defaultConfig from "./config";
export default {
  name: "index",
  data() {
    return {
      spinShow: true,
      customEditor: null,
      codeModal: false,
      editCode: "",
      editModal: false,
      typeArr: [
        {
          type: "热读好文",
          fn: "handleResponse",
          class: "",
          style: `word-break: normal;
          margin:15px auto;
          font-size:16px;
          line-height:30px;
          color:#444;`
        },
        {
          type: "今日轻听",
          fn: "none",
          class: "todyExpCont",
          style: ""
        },
        {
          type: "周末荐书",
          fn: "none",
          class: "paragraph",
          style: `margin:15px auto 0;
          font-size:16px;
          line-height:36px`
        },
        {
          type: "读笔记",
          childType: [
            {
              type: "精选语录",
              fn: "noteSel"
            },
            {
              type: "上篇",
              fn: "noteUp"
            },
            {
              type: "中篇",
              fn: "noteMid"
            },
            {
              type: "下篇",
              fn: "noteDown"
            }
          ],
          fn: "none",
          class: "",
          style: `margin:15px auto;
          line-height:22px;
          font-size:16px;
          color:#333`
        },
        {
          type: "听世界",
          fn: "masterRes",
          class: "",
          style: `margin:17px auto;
          line-height:30px;
          font-size:14px;
          color:#555`
        },
        {
          type: "直达签单",
          fn: "none",
          class: "",
          style: ""
        }
      ],
      defaultIndex: 0,
      checkFn: '',
      name: '',
      isFile: false
    };
  },
  computed: {
    code() {
      if (this.typeArr[this.defaultIndex].fn !== "none" && this.customEditor) {
        this.customEditor = this.customEditor.replace(/"/g, "'");
        this.customEditor = this.customEditor.replace(/[\(\)]/g, "");
        return this.typeArr[this.defaultIndex].fn + '("' + this.customEditor + '")'
      } else if (this.typeArr[this.defaultIndex].childType && this.checkFn) {
        this.customEditor = this.customEditor.replace(/"/g, "'");
        this.customEditor = this.customEditor.replace(/[\(\)]/g, "");
        return this.checkFn + '("' + this.customEditor + '")'
      } else {
        return this.customEditor;
      }
    }
  },
  methods: {
    initControl() {
      var _this = this;
      window.addEventListener('message', function(e){
        console.log(e.origin, window.location.origin)
        if (e.origin !== window.location.origin) {
          _this.name = e.data.name ? e.data.name : ''
          _this.isFile = e.data.isFile ? true : false
          if (e.data.isFile && e.data.content) {
            let data = qs.stringify({
              fileUrl: e.data.content
            })
            axios.post('/common/downloadhtml', data).then(res => {
              // console.log(res)
              if(res.status===200&&res.data.status==="100000") {
                _this.editCode = res.data.data
                _this.setContent()
              } else {
                this.$Message.error({
                  content: "内容读取失败!"
                })
              }
            })
          } else {
            _this.editCode = e.data.content
            _this.setContent()
          }
        }
      })
    },
    uploadFile() {
      var _this = this
      if (this.code) {
        if (this.isFile) {
          let data = qs.stringify({
            content: this.code
          })
          axios.post('/common/uploadhtml', data).then(res => {
            // console.log(res)
            if(res.status===200&&res.data.status==="100000") {
              this.$Message.success({
                content: "上传成功!",
                onClose: () => {
                  window.parent.postMessage({
                    name: _this.name,
                    content: res.data.data
                  }, "*");
                }
              })
            } else {
              this.$Message.error({
                content: "上传失败!"
              })
            }
          })
        } else {
          this.$Message.success({
            content: "编辑成功!",
            onClose: () => {
              window.parent.postMessage({
                name: _this.name,
                content: _this.code
              }, "*");
            }
          })
        }
      } else {
        this.$Message.warning({
          content: "请添加内容后再上传代码!"
        })
      }
    },
    setContent() {
      let content = this.editCode
      let start = content.indexOf('("')
      let end = content.indexOf('")')
      if (start!==-1 && end!==-1) {
        content = content.substring(start+2, end)
      } 
      tinymce.get("tinymceEditer").setContent(content);
      this.editModal = false;
    },
    edit() {
      this.editCode = "";
      this.editModal = true;
    },
    reset() {
      if (tinymce.get("tinymceEditer")) {
        tinymce.get("tinymceEditer").destroy();
        this.init();
      }
    },
    trans() {
      let newContent = tinymce
        .get("tinymceEditer")
        .selection
        .getContent()
        .replace(/(<\/p>)(\s*)(<p)([\s\d\w#=:;"'\(\),.-]*)(>)/g, "<br>");
      tinymce.get("tinymceEditer").selection.setContent(newContent)
    },
    handleSuccess(res) {
      this.customEditor = res;
      tinymce.get("tinymceEditer").setContent(this.customEditor)
    },
    init() {
      let vm = this;
      tinymce.init({
        selector: "#tinymceEditer",
        width: 375,
        min_height: 540,
        max_width: 420,
        ...defaultConfig,
        forced_root_block_attrs: {
          class: vm.typeArr[this.defaultIndex].class === '' ? undefined : vm.typeArr[this.defaultIndex].class,
          style: vm.typeArr[this.defaultIndex].style === '' ? undefined : vm.typeArr[this.defaultIndex].style
        },
        setup: function(editor) {
          editor.on("init", function(e) {
            vm.spinShow = false;
          });
          editor.on('PreProcess', function (e) {
            let nodes = e.node.childNodes
            console.log('生成代码是删掉的空节点：')
            for(var i=0;i<nodes.length;i++){
              if (/^\s*$/.test(nodes[i].innerText) && nodes[i].nodeName === 'P' && nodes[i].innerHTML.indexOf('src') === -1) {
                console.log(nodes[i])
                e.node.removeChild(nodes[i])
              }
            }
          });
          editor.addButton("br", {
            title: "段落转换行",
            image: "./static/br.png",
            onclick: function() {
              vm.trans()
            }
          });
          editor.addButton("clear", {
            title: "清空",
            image: "./static/clear.png",
            onclick: function() {
              editor.setContent("");
            }
          });
          editor.addButton("edit", {
            title: "修改",
            image: "./static/eraser.png",
            onclick: function() {
              vm.edit();
            }
          });
          editor.addButton("certain", {
            title: "生成代码",
            image: "./static/certain.png",
            onclick: function() {
              if (tinymce.get("tinymceEditer").getContent()) {
                vm.handleSubmit();
              } else {
                vm.$Message.warning({
                  content: "输入内容后再生成!"
                })
              }
            }
          });
        }
      });
    },
    handleSubmit() {
      // console.log('生成：' + tinymce.get("tinymceEditer").getContent())
      axios.post('/minify', {
        content: tinymce.get("tinymceEditer").getContent()
      }).then(res => {
        // console.log(res)
        if (res.status === 200) {
          this.customEditor = res.data;
        } else {
          this.customEditor = tinymce.get("tinymceEditer").getContent();
          this.$Message.error({
            content: "压缩失败！"
          })
        }
        this.codeModal = true;
      })
      
    },
    handleReset() {
      tinymce.get("tinymceEditer").setContent("");
    },
    parseQuery(query){
      var queryObj = {};
      var reg = /[?&]([^=&#]+)=([^&#]*)/g;
      var querys = window.location.href.match(reg);
      if (querys) {
          // for (var i in querys) {
          for (var i = 0; i < querys.length; i++) {
              if (querys[i]) {
                  var query = querys[i].split('=');
              }
              var key = query[0].substr(1),
                  value = query[1];
              // queryObj[key] ? queryObj[key] = [].concat(queryObj[key], value) : queryObj[key] = value;
              queryObj[key] ? queryObj[key] = queryObj[key] : queryObj[key] = value;
              if (!(queryObj[key]) || queryObj[key] == "undefined" || queryObj[key] == "(null)" || queryObj[key] == "null") {
                  queryObj[key] = "";
              } else {
                  queryObj[key] = queryObj[key]
              }
          }
      } else {
          queryObj["token"] = "";
      }
      return queryObj;
    }
  },
  created() {
    let params = this.parseQuery()
    if (params["type"]) {
      this.defaultIndex = Number(params["type"])
    }
  },
  mounted() {
    this.init();
    this.initControl()
  },
  destroyed() {
    tinymce.get("tinymceEditer").destroy();
  }
};
</script>
<style>
.modalbody {
  height: 400px;
  overflow: scroll;
}
.radio-box {
  /* padding: 10px; */
  display: inline-block;
  overflow: hidden;
}
.radio-box input[type="text"] {
  width: 450px;
}
.radio-box,
.set-els {
  color: #666;
  font-weight: bold;
}
.radio-box {
  margin-right: 15px;
}
.radio-box label {
  background-color: white;
  border-radius: 0px;
  border: 1px solid #2d8cf0;
  width: 20px;
  height: 20px;
  display: inline-block;
  text-align: center;
  vertical-align: middle;
  line-height: 20px;
}
.radio-box label:hover {
  cursor: pointer;
}
.radio-box.checked {
  color: #2d8cf0;
}
.radio-box.checked label {
  background-color: #2d8cf0;
}
.radio-box.checked label:after {
  content: "\2714";
  color: white;
}
.radio-box input[type="radio"] {
  display: none;
}
.radio-box .label {
  margin-right: 2px;
  cursor: pointer;
}
</style>